import fs from 'fs';
import _ from 'lodash';
import path from 'path';

const __dirname = path.resolve();
const PLUGIN_PATH = path.join(__dirname, 'plugins', 'Tlon-Sky');

export const SKY_PATH = {
    user: path.join(PLUGIN_PATH, 'data', 'USER'),
    group: path.join(PLUGIN_PATH, 'data', 'GROUP'),
    config: path.join(PLUGIN_PATH, 'config', 'config.json'),
    map: path.join(PLUGIN_PATH, 'data', 'map.json')
};
export const MAP_LIST = [
    '遇境', '云巢',
    '晨岛', '预言山谷', '夜行石',
    '云野', '圣岛', '云峰',
    '雨林', '大树屋', '风行网道',
    '霞谷', '圆梦村', '雪隐峰', '圆梦村剧场', '音乐商店',
    '暮土', '遗忘方舟', '藏宝岛礁',
    '禁阁', '办公室', '星光沙漠', '庇护所', '月牙绿洲',
    '伊甸'
]

/** 地图列表 */
const mapList = [
    '遇境', '云巢',
    '晨岛', '预言山谷', '夜行石',
    '云野', '圣岛', '云峰',
    '雨林', '大树屋', '风行网道',
    '霞谷', '圆梦村', '雪隐峰', '圆梦村剧场', '音乐商店',
    '暮土', '遗忘方舟', '藏宝岛礁',
    '禁阁', '办公室', '星光沙漠', '庇护所', '月牙绿洲',
    '伊甸'
];

if (!fs.existsSync(SKY_PATH['map'])) SD(SKY_PATH['map'], {
    遇境: [], 云巢: [],
    晨岛: [], 预言山谷: [], 夜行石: [],
    云野: [], 圣岛: [], 云峰: [],
    雨林: [], 大树屋: [], 风行网道: [],
    霞谷: [], 圆梦村: [], 雪隐峰: [], 圆梦村剧场: [], 音乐商店: [],
    暮土: [], 遗忘方舟: [], 藏宝岛礁: [],
    禁阁: [], 办公室: [], 星光沙漠: [], 庇护所: [], 月牙绿洲: [],
    伊甸: []
});
if (!fs.existsSync(SKY_PATH['config'])) SD(SKY_PATH['config'], { a: 20, b: 5, c: 60, d: 1 });
/** 
fs.readdir(SKY_PATH['user'], (err, files) => {
    if (err) {
        logger.error('读取文件夹错误:', err);
        return;
    }

    files.forEach(file => {
        if (path.extname(file) === '.json') {
            const filePath = path.join(SKY_PATH['user'], file);
            fs.readFile(filePath, 'utf8', (err, data) => {
                if (err) {
                    logger.error('读取文件错误:', err);
                    return;
                }

                try {
                    const jsonData = JSON.parse(data);
                    if (!jsonData.hasOwnProperty('GROUP')) {
                        jsonData.GROUP = "";
                        fs.writeFile(filePath, JSON.stringify(jsonData, null, 2), 'utf8', (err) => {
                            if (err) {
                                logger.error('写入文件错误:', err);
                            } else { }
                        });
                    }
                } catch (error) {
                    logger.error('解析JSON出错:', error);
                }
            });
        }
    });
});
/** */
const REG_1 = /^(#|\/)传送(.*)$/;
const REG_2 = /^(#|\/)?设置((团队)?(昵称|名称))(:|：)(.*)$/;
export class SKY extends plugin {
    constructor() {
        super({
            name: '[Tlon-Sky]娱乐',
            dsc: 'Tlon-Sky',
            event: 'message',
            priority: 1,
            rule: [
                { reg: /^(#|\/)?结束跑图$/, fnc: 'F_4' },
                { reg: /^(#|\/)?跑图状态$/, fnc: 'F_5' },
                { reg: /^(#|\/)?光遇地图$/, fnc: 'F_6' },
                { reg: REG_1, fnc: 'F_7' },
                { reg: REG_2, fnc: 'F_8' },
                { reg: /^(#|\/)?(建立|创建)团队$/, fnc: 'F_9' },
                { reg: /^(#|\/)?团队信息$/, fnc: 'F_10' },
                { reg: /^(#|\/)?查看玩家(.*)$/, fnc: 'F_11' },
                { reg: /^(#|\/)?(光遇|白蜡|季蜡)排行榜$/, fnc: 'F_12' }
            ]
        })
    }

    /** 结束跑图 */
    async F_4(e) {
        if (!IEU(e)) return
        const UID = e.user_id
        const UF = `${SKY_PATH['user']}/${UID}.json`
        const CD = GCD()

        const UD = JSON.parse(fs.readFileSync(UF, 'utf8'))
        const MAP_DATA = JSON.parse(fs.readFileSync(SKY_PATH['map'], 'utf8'))

        if (!UD['SIMULATED_STATE'])
            return e.reply([
                segment.at(UID),
                `\n您当前并没有在跑图呢`
            ])

        const TT = GTT(UD['TIMESTAMP'])
        const RM = mapList[Math.floor(Math.random() * mapList.length)]
        const UL = UD['LOCATION']
        const H = TT['H']
        const M = TT['M']
        const S = TT['S']

        let GC1 = ((H * 60) + M) * CD['d']
        let T = ''
        if (GC1 > CD['c']) {
            T = `理论获得白蜡[${GC1}]，但超出上限，所以`
            GC1 = CD['c']
        }

        UD['SIMULATED_STATE'] = false
        UD['CURRENCY_1'] += GC1
        UD['LOCATION'] = RM
        MAP_DATA[UL] = MAP_DATA[UL].filter(item => item !== UD['ID'])
        MAP_DATA[RM].push(UD['ID'])
        SD(SKY_PATH['map'], MAP_DATA)
        SD(UF, UD)

        return e.reply([
            segment.at(UID),
            `\n已结束本次跑图\n本次跑图抵达[${RM}]\n用时[${H}]时[${M}]分[${S}]秒\n${T}获得白蜡[${GC1}]`
        ])
    }

    /** 跑图状态 */
    async F_5(e) {
        if (!IEU(e)) return
        const UID = e.user_id
        const UF = `${SKY_PATH['user']}/${UID}.json`
        const CD = GCD()

        const UD = JSON.parse(fs.readFileSync(UF, 'utf8'))

        if (!UD['SIMULATED_STATE'])
            return e.reply([
                segment.at(UID),
                `\n您当前并没有在跑图呢`
            ])

        const TIME_TAKEN = GTT(UD['TIMESTAMP'])
        const H = TIME_TAKEN['H']
        const M = TIME_TAKEN['M']
        const S = TIME_TAKEN['S']

        return e.reply([
            segment.at(UID),
            `正在跑图中\n已跑图[${H}]时[${M}]分[${S}]秒\n每分钟[${CD['d']}]白蜡 | 上限[${CD['c']}]白蜡`
        ])
    }

    /** 光遇地图 */
    async F_6(e) {
        if (!IEU(e)) return
        // 先执行一遍这个
        addarray()
        const UID = e.user_id
        const UFP = `${SKY_PATH['user']}/${UID}.json`

        const UD = JSON.parse(fs.readFileSync(UFP, 'utf8'))
        const MAP_DATA = JSON.parse(fs.readFileSync(SKY_PATH['map'], 'utf8'))

        const USER_LOCATION = UD['LOCATION']
        const LOCATION_NUMBER = MAP_DATA[USER_LOCATION].length - 1
        const MAP_LISTS = MAP_LIST.filter(item => item !== UD['LOCATION'])

        let OTHER_LOCATION_NUMBER = []
        for (let i = 0; i < MAP_LISTS.length; i++) {
            OTHER_LOCATION_NUMBER.push(` ${MAP_LISTS[i]} [${MAP_DATA[MAP_LISTS[i]].length}]人\r`)
        }
        OTHER_LOCATION_NUMBER = OTHER_LOCATION_NUMBER.join('').slice(0, -1)

        return e.reply([
            segment.at(UID),
            `\n您所处 [${USER_LOCATION}]\n同一地图玩家数: ${LOCATION_NUMBER}\n其他位置玩家人数\n${OTHER_LOCATION_NUMBER}`,
        ])
    }

    /** 传送 */
    async F_7(e) {
        if (!IEU(e)) return
        const UID = e.user_id
        const UF = `${SKY_PATH['user']}/${UID}.json`

        const LOCATION = e.msg.match(REG_1)[2].replace(/\s/g, '');
        if (!mapList.includes(LOCATION))
            return e.reply([
                segment.at(UID),
                '\n没有这个地图\n您可以发送[光遇地图]查看可传送地图'
            ])

        const UD = JSON.parse(fs.readFileSync(UF, 'utf8'))
        const MAP_DATA = JSON.parse(fs.readFileSync(SKY_PATH['map'], 'utf8'))

        if (UD['SIMULATED_STATE'])
            return e.reply([
                segment.at(UID),
                '\n当前正在模拟跑图，无法传送！'
            ])
        const USER_LOCATION = UD['LOCATION']
        if (LOCATION === USER_LOCATION)
            return e.reply([
                segment.at(UID),
                '\n您已经在这个地图了\n您可以发送[光遇地图]查看可传送地图'
            ])

        const TIME = _.random(2000, 6000)

        e.reply([
            segment.at(UID),
            '\n开始传送，请稍等'
        ])

        UD['LOCATION'] = LOCATION
        MAP_DATA[USER_LOCATION] = MAP_DATA[USER_LOCATION].filter(item => item !== UD['ID'])
        MAP_DATA[LOCATION].push(UD['ID'])
        SD(UF, UD)
        SD(SKY_PATH['map'], MAP_DATA)

        setTimeout(function () {
            return e.reply([
                segment.at(UID),
                `\n传送成功！\n您已抵达[${LOCATION}]\n耗时[${(TIME / 1000).toFixed(2)}]秒`
            ])
        }, TIME);
    }

    /** 设置((团队)昵称) */
    async F_8(e) {
        if (!IEU(e)) return
        const UID = e.user_id
        const UF = `${SKY_PATH['user']}/${UID}.json`

        const MATCH = e.msg.match(REG_2)
        const SETTINGS = MATCH[2]
        const SETTINGS_CONTENT = MATCH[6]

        const UD = JSON.parse(fs.readFileSync(UF, 'utf8'))
        if (/^(昵称|名称)/.test(SETTINGS)) {
            if (SETTINGS_CONTENT.length < 2 || SETTINGS_CONTENT.length > 12)
                return e.reply([
                    segment.at(UID),
                    `\n设置失败！\n昵称长度小于2位或大于12位\n请重新设置`
                ])

            UD['GAME_NICKNAME'] = SETTINGS_CONTENT
            SD(UF, UD)

            return e.reply([
                segment.at(UID),
                `\n设置成功！\n您的新昵称[${SETTINGS_CONTENT}]`
            ])
        } else if (/^团队(昵称|名称)/.test(SETTINGS)) {
            const GROUP_FILE = SKY_PATH['group'] + '/' + UD['GROUP'] + '.json'

            if (UD['GROUP'] === '') // 无团队
                return e.reply([
                    segment.at(UID),
                    '\n您尚未创建团队'
                ])


            if (SETTINGS_CONTENT.length < 2 || SETTINGS_CONTENT.length > 8)
                return e.reply([
                    segment.at(UID),
                    `\n设置失败！\n长度小于2位或大于8位\n请重新设置`
                ])

            const GROUP_DATA = JSON.parse(fs.readFileSync(GROUP_FILE, 'utf8'))

            if (GROUP_DATA['LEADER'] !== UID)
                return e.reply([
                    segment.at(UID),
                    '\n您不是团长！\n无法设置团名'
                ])

            GROUP_DATA['NACKNAME'] = SETTINGS_CONTENT
            SD(GROUP_FILE, GROUP_DATA)

            return e.reply([
                segment.at(UID),
                `\n设置成功！\n团队新昵称[${SETTINGS_CONTENT}]`
            ])
        }
    }

    /** 创建团队 */
    async F_9(e) {
        if (!IEU(e)) return
        const UID = e.user_id
        const UF = `${SKY_PATH['user']}/${UID}.json`
        const UD = JSON.parse(fs.readFileSync(UF, 'utf8'))

        if (UD['CURRENCY_1'] < 10000 && UD['CURRENCY_2'] < 320)
            return e.reply([
                segment.at(UID),
                '\n资金不足！\n需要白蜡[10000] | 季蜡[320]'
            ])

        if (UD['GROUP'] !== '')
            return e.reply([
                segment.at(UID),
                '您已经有团了\n请先退出再建立团队'
            ])

        const GROUP_FILE = SKY_PATH['group'] + '/' + UID + '.json'
        const GROUP_NUMBER = (fs.readdirSync(SKY_PATH['group']).length) + 1

        UD['CURRENCY_1'] -= 10000
        UD['CURRENCY_2'] -= 320
        UD['GROUP'] = `${UID}`
        SD(UF, UD)
        SD(GROUP_FILE, {
            FOUNDER: UID, // 创建者ID
            LEADER: UID, // 团长ID
            NACKNAME: `未命名团队${GROUP_NUMBER}`, // 团队名称
            GROUP_ID: GROUP_NUMBER, // 团队ID
            MEMBERS: [], // 团队成员
            CONTRIBUTIONS_POOL: 0, // 贡献池数量
            CONTRIBUTIONS_LEVEL: 0 // 贡献池等级
        })

        return e.reply([
            segment.at(UID),
            `\n创建成功！\n团队编号[${GROUP_NUMBER}]\n团队昵称[未命名团队${GROUP_NUMBER}]\n可用指令[设置团队昵称:(名称)]来设置名称`
        ])
    }

    /** 团队信息 */
    async F_10(e) {
        if (!IEU(e)) return
        const UID = e.user_id
        const UD = JSON.parse(fs.readFileSync(`${SKY_PATH['user']}/${UID}.json`, 'utf8'))

        if (UD['GROUP'] === '') return e.reply([
            segment.at(UID),
            '\n您尚未加入(或创建)团队'
        ])

        const GROUP_DATA = JSON.parse(fs.readFileSync(SKY_PATH['group'] + '/' + UD['GROUP'] + '.json', 'utf8'))

        let LEADER_NICKNAME = UD['GAME_NICKNAME']
        if (GROUP_DATA['LEADER'] !== UID) {
            const LEADER_DATA = JSON.parse(fs.readFileSync(SKY_PATH['user'] + GROUP_DATA['LEADER'] + '.json', 'utf8'))
            LEADER_NICKNAME = LEADER_DATA['GAME_NICKNAME']
        }

        return e.reply([
            segment.at(UID),
            `\n[${GROUP_DATA['GROUP_ID']}]${GROUP_DATA['NACKNAME']}`,
            `\n团长 [${LEADER_NICKNAME}]`,
            `\n团队成员数量 [${GROUP_DATA['MEMBERS'].length}]位`,
            `\n贡献池数量 [${GROUP_DATA['CONTRIBUTIONS_POOL']}] | 等级 [${GROUP_DATA['CONTRIBUTIONS_LEVEL']}]`
        ])
    }

    /** 查看玩家 */
    async F_11(e) {
        if (!IEU(e)) return
        const UID = e.user_id
        const UD = JSON.parse(fs.readFileSync(`${SKY_PATH['user']}/${UID}.json`, 'utf8'))
        const MAP_DATA = JSON.parse(fs.readFileSync(SKY_PATH['map'], 'utf8'))
        const NEARBY_USER = MAP_DATA[UD['LOCATION']]

        if (/^(#|\/)?查看玩家$/.test(e.msg)) {
            let REPLY_ARRAY = []
            let USER_NUMBER = NEARBY_USER.length > 10 ? 10 : NEARBY_USER.length
            for (let i = 0; i < USER_NUMBER; i++) {
                const USER_DATAS = JSON.parse(fs.readFileSync(SKY_PATH['user'] + NEARBY_USER[i] + '.json', 'utf8'))
                REPLY_ARRAY.push(`${i + 1}、[${USER_DATAS['GAME_NICKNAME'].replace(/_/, '')}]`)
                if (e.adapter !== 'QQBot') REPLY_ARRAY.push('\n')
            }

            return e.reply([
                segment.at(UID),
                '\n附近玩家(最高展示十位)\n',
                ...REPLY_ARRAY
            ])
        } else {
            const SERIAL_NUMBER = parseInt(e.msg.replace(/#|\/|查看玩家/, '').replace(/\s/g, '')) - 1

            if (typeof SERIAL_NUMBER !== 'number' && isNaN(SERIAL_NUMBER))
                return e.reply([
                    segment.at(UID),
                    '请输入纯数字！'
                ])

            const QUERYING_USER_DATA = JSON.parse(fs.readFileSync(SKY_PATH['user'] + NEARBY_USER[SERIAL_NUMBER] + '.json', 'utf8'))

            let GROUP_DATA = '暂未加入团队'
            if (QUERYING_USER_DATA['GROUP'] !== '') {
                GROUP_DATA = JSON.parse(fs.readFileSync(SKY_PATH['group'] + '/' + QUERYING_USER_DATA['GROUP'] + '.json', 'utf8'))
                GROUP_DATA = GROUP_DATA['NACKNAME']
            }

            return e.reply([
                segment.at(UID),
                `\n[${QUERYING_USER_DATA['GAME_ID']}]${QUERYING_USER_DATA['GAME_NICKNAME']}`,
                `\n最近签到日期 [${QUERYING_USER_DATA['LAST_DATE']}]`,
                `\n累计签到次数 [${QUERYING_USER_DATA['ACCUMULATE']}]`,
                `\n所在位置 [${QUERYING_USER_DATA['LOCATION']}]`,
                `\n白蜡 [${QUERYING_USER_DATA['CURRENCY_1']}] | 季蜡 [${QUERYING_USER_DATA['CURRENCY_2']}]`,
                `\n模拟跑图状态 [${QUERYING_USER_DATA['SIMULATED_STATE']}]`,
                `\n团队 [${GROUP_DATA}]`
            ])
        }
    }

    async F_12(e) {
        const FL = fs.readdirSync(SKY_PATH['user']);

        let C1 = [];
        let C2 = [];

        FL.forEach(F => {
            if (path.extname(F) === '.json') {
                const FP = path.join(SKY_PATH['user'], F);
                const UD = JSON.parse(fs.readFileSync(FP, 'utf8'));

                const UD_GID = UD['GAME_ID']
                const UD_C1 = UD['CURRENCY_1']
                const UD_C2 = UD['CURRENCY_2']

                C1.push({ UD_GID, UD_C1 });
                C2.push({ UD_GID, UD_C2 })
            }
        });

        C1.sort((a, b) => b.UD_C1 - a.UD_C1);
        C2.sort((a, b) => b.UD_C2 - a.UD_C2);
        C1 = C1.slice(0, 12)
        C2 = C2.slice(0, 12)

        // 返回排名
        const C1SR = C1.map((item, index) => `># No.${index + 1} ➠➠ID: ${item.UD_GID}\n白蜡[${item.UD_C1}]\n`);
        const C2SR = C2.map((item, index) => `># No.${index + 1} ➠➠ID: ${item.UD_GID}\n季蜡[${item.UD_C2}]\n`);

        const RT = e.msg.match(/^(#|\/)?(白蜡|季蜡|光遇)排行榜$/)[2]
        if (RT === '光遇') return e.reply([
            '> 选择排行榜查看',
            Bot.Button([[{ label: '白蜡', callback: '白蜡排行榜' }, { label: '季蜡', callback: '季蜡排行榜' }]])
        ])
        if (RT === '白蜡') return FR(e, RT, C1SR)
        if (RT === '季蜡') return FR(e, RT, C2SR)
    }
}

/** 计算用时 */
function GTT(ST) {
    const TD = Date.now() - ST
    const H = Math.floor(TD / 3600000)
    const M = Math.floor((TD % 3600000) / 60000)
    const S = Math.floor((TD % 60000) / 1000)
    return { H, M, S }
}

/** 读取配置 */
function GCD() {
    const DATA = JSON.parse(fs.readFileSync(SKY_PATH['config'], 'utf8'))
    /** 签到获得白蜡 */
    const a = DATA['a']
    /** 签到获得季蜡 */
    const b = DATA['b']
    /** 模拟跑图上限 */
    const c = DATA['c']
    /** 模拟跑图1分钟多少白蜡 */
    const d = DATA['d']
    return { a, b, c, d }
}

/** 是否存在用户 */
function IEU(e) {
    const UID = e.user_id
    if (!fs.existsSync(`${SKY_PATH['user']}/${UID}.json`)) {
        e.reply([
            segment.at(UID),
            '\n没有您的用户信息，请先发送[光遇签到]创建'
        ])
        return false
    }
    return true
}

/** 存储
 * @FILE 位置
 * @DATA 数据
 */
function SD(FILE, DATA) { fs.writeFileSync(FILE, JSON.stringify(DATA, null, 4), 'utf8') }

function addarray() {
    const MAP_DATA = JSON.parse(fs.readFileSync(SKY_PATH['map'], 'utf8'))
    fs.readdir(SKY_PATH['user'], (err, files) => {
        if (err) {
            logger.error('Error reading folder:', err);
            return;
        }

        files.forEach(file => {
            if (path.extname(file) === '.json') {
                const filePath = path.join(SKY_PATH['user'], file);
                const data = fs.readFileSync(filePath, 'utf8');
                const json = JSON.parse(data);

                const location = json.LOCATION;
                const id = json.ID;

                if (!MAP_DATA[location].includes(id)) {
                    MAP_DATA[location].push(id);
                }
            }
        });
        SD(SKY_PATH['map'], MAP_DATA)
    });
}

function FR(e, RT, RD) {
    return e.reply([
        `${RT}排行榜\n`,
        ...RD
    ]);
}